﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Crosland.Automotriz.Facade.Interface;
using Crosland.Automotriz.Facade.Facade;
using Crosland.Automotriz.Core;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using Crosland.Automotriz.Logic.Linq;
using System.Data;
using DevExpress.Web.ASPxEditors;
using System.Configuration;

namespace Crosland.Automotriz.Web.Repuestos
{
    public partial class wFrmManualesPartesVehiculosSistemaModeloActualizar : System.Web.UI.Page
    {

        iFacadeSistema cls_man_modelo_imagenlogic = new FacadeSistema();
        string idNegocio = ConfigurationManager.AppSettings["Negocio"];
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", "JavaScript:confirmSubmitResult();", true);
                this.listarImagen();
            
            }
        }   


        void listarImagen() {
            try
            {
            DVimagenes.DataSource = cls_man_modelo_imagenlogic.listarT_Man_Modelo_Imagen(Convert.ToInt32(Session["id_modelo"]));
            DVimagenes.DataBind();
            }
            catch 
            {
                
             
            }


           
        
        
        }


      

        protected void btnPopAgregar_Click(object sender, EventArgs e)
        {

            clsT_Man_Modelo_ImagenLogic clsModeloImagen = new clsT_Man_Modelo_ImagenLogic();

                int id_imagen=clsModeloImagen.UltimoNumero()+1;



            if (UploadControl.FileName.Length == 0)
            {

                return;
            }
            else
            {
                T_MAN_MODELO_IMAGEN t_man_modelo_imagen = new T_MAN_MODELO_IMAGEN();
                t_man_modelo_imagen.ID_MODELO = Convert.ToInt32(Session["id_modelo"]);
                t_man_modelo_imagen.DES_IMAGEN = "Modelo_" +id_imagen+"_" + Session["id_modelo"] + UploadControl.FileName.Substring(UploadControl.FileName.Length - 4);
                t_man_modelo_imagen.ID_IMAGEN = cls_man_modelo_imagenlogic.UltimoNumero() + 1;
                cls_man_modelo_imagenlogic.Insertar(t_man_modelo_imagen);
                this.GuardarImg();

                imagenModelo.ImageUrl = ConfigurationManager.AppSettings["RutaFotoModelo"]+"/" + "Modelo_" + id_imagen + "_" + Session["id_modelo"] + UploadControl.FileName.Substring(UploadControl.FileName.Length - 4);

            }


            this.listarImagen();

        }



        void GuardarImg()
        {


            try
            {
                if (UploadControl.HasFile)
                {

                    string ext = UploadControl.PostedFile.FileName;
                    ext = ext.Substring(ext.LastIndexOf(".") + 1).ToLower();
                    string[] formatos =
                      new string[] { "jpg", "jpeg", "bmp", "png", "gif" };
                    if (Array.IndexOf(formatos, ext) < 0)
                        lblMsj.Text = ("Formato de imagen inválido.");

                    else
                    {

                        GuardarArchivo(UploadControl.PostedFile);

                    }
                }
            }
            catch (Exception ex)
            {
                lblMsj.Text = (ex.Message);
            }

        }











        private void GuardarArchivo(HttpPostedFile file)
        {
            clsT_Man_Modelo_ImagenLogic clModeloImage=new clsT_Man_Modelo_ImagenLogic();
            int id_imagen = clModeloImage.UltimoNumero();

            string ruta = Server.MapPath(ConfigurationManager.AppSettings["RutaFotoModelo"]);


            if (!Directory.Exists(ruta))
                Directory.CreateDirectory(ruta);

            string archivo = String.Format("{0}\\{1}", ruta, "Modelo_" +id_imagen+"_" + Session["id_modelo"] + UploadControl.FileName.Substring(UploadControl.FileName.Length - 4));


            System.Drawing.Image img = RedimensionarImagen(file.InputStream);


            if (File.Exists(archivo))
                lblMsj.Text = (String.Format("Ya existe una imagen con nombre\"{0}\".", "Modelo_" +id_imagen+"_" + Session["id_modelo"] + UploadControl.FileName.Substring(UploadControl.FileName.Length - 4)));
            else
            {

                string ext = file.ContentType.Substring(
                  file.ContentType.LastIndexOf("/") + 1);
                ImageFormat format;
                switch (ext)
                {
                    case "gif":
                        format = ImageFormat.Gif;
                        break;
                    case "bmp":
                        format = ImageFormat.Bmp;
                        break;
                    case "png":
                        format = ImageFormat.Png;
                        break;
                    default:
                        format = ImageFormat.Jpeg;
                        break;
                }
                img.Save(archivo, format);
            }
        }



        private static System.Drawing.Image RedimensionarImagen(Stream stream)
        {

            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);

            const int max = 500;

            int h = img.Height;
            int w = img.Width;
            int newH, newW;

            if (h > w && h > max)
            {

                newH = max;
                newW = (w * max) / h;
            }
            else if (w > h && w > max)
            {

                newW = max;
                newH = (h * max) / w;
            }
            else
            {
                newH = h;
                newW = w;
            }
            if (h != newH && w != newW)
            {

                Bitmap newImg = new Bitmap(img, newW, newH);
                Graphics g = Graphics.FromImage(newImg);
                g.InterpolationMode =
                  System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
                g.DrawImage(img, 0, 0, newImg.Width, newImg.Height);
                return newImg;
            }
            else
                return img;
        }

        protected void btnSalir_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Repuestos/wFrmManualesPartesVehiculosModelo.aspx?id=" + idNegocio);
        }

        protected void btnPopAceptar_Click(object sender, EventArgs e)
        {

            try
            {
                T_MAN_MODELO_IMAGEN t_man_modelo_imagen = new T_MAN_MODELO_IMAGEN();
                t_man_modelo_imagen.ID_IMAGEN = Convert.ToInt32(Session["id_imagen"]);


                cls_man_modelo_imagenlogic.eliminarT_Man_Modelo_Imagen(t_man_modelo_imagen);

                this.listarImagen();

                string archivo = Server.MapPath(ConfigurationManager.AppSettings["RutaFotoModelo"]+"/Modelo_" + Session["id_imagen"] + "_" + Session["id_modelo"]);
               

                if (File.Exists(archivo+".jpg"))
                {
                    System.IO.File.Delete(archivo+".jpg");
                }
                if (File.Exists(archivo + ".png")) {

                    System.IO.File.Delete(archivo+".png");
                }
                if (File.Exists(archivo + ".bmp"))
                {

                    System.IO.File.Delete(archivo+".bmp");
                }

            }catch(IOException){
                return;
            
            
            }

            catch 
            {
          
               
            }

            






        }

   

        protected void DVimagenes_ItemCommand(object source, DevExpress.Web.ASPxDataView.DataViewItemCommandEventArgs e)
        {
            try
            {
            Session["id_imagen"]=Convert.ToInt32(e.CommandArgument);

            string script = " ShowEliminar();";
            ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", script, true);
            }
            catch 
            {}
           
         
            

        }

     
    }
}